<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script>

// 异步控制并发数
// function limitRequest(urls = [], limit = 3) {
//     return new Promise((reslove, reject)=>{
//         const len = urls.length
//         let count = 0

//         while (limit > 0) {
//             start()
//             limit -= 1
//         }

//         function start(){
//             const url = urls.shift()
//             if(url){
//                 fetch(url).then(()=>{
//                     if(count === len - 1){
//                         reslove()
//                     }else{
//                         count ++
//                         start()
//                     }
//                 })
//             }
//         }
//     })

// }


function limitRequest(urls, limit){
    return new Promise((reslove, reject)=>{
        let len = urls.length
        const results = new Array(len)
        while(limit > 0 && urls.length > 0 ){
            send(urls.shift(), len - urls.length - 1)
            limit -= 1
        }

        function send(url, index){
            fetch(url)
                .then(response => response.json())
                .then(res=>{
                results[index] = res
                if(urls.length > 0){
                    send(urls.shift(), len - urls.length - 1)
                }else{
                    reslove(results)
                }
            })
        }
    })
}

const urls = [
    'http://127.0.0.1:91/a?id=1',
    'http://127.0.0.1:91/a?id=2',
    'http://127.0.0.1:91/a?id=3',
    'http://127.0.0.1:91/a?id=4',
    'http://127.0.0.1:91/a?id=5',
    'http://127.0.0.1:91/a?id=6',
]



limitRequest(urls, 3).then(res=>{
    console.log(res)
})

    </script>
</body>
</html>